<template>
  <div>
    <div>
      <input v-model="stationNameInput" placeholder="请输入站名" />
      <button @click="fetchWeatherDataByName">查询</button>
      <button @click="toggleLocationSelector">地点选择</button>
      <button @click="toggleChartsVisibility">{{ isChartsVisible ? '隐藏图表' : '显示图表' }}</button>
      <button @click="toggleMapVisibility">{{ isMapVisible ? '隐藏地图' : '显示地图' }}</button>
    </div>

    <!-- 一级菜单：选择省份（模态框样式） -->
    <div v-if="isLocationSelectorVisible" class="location-selector-overlay">
      <div class="location-selector">
        <div class="location-header">
          <span>选择省份</span>
          <button @click="toggleLocationSelector">关闭</button>
        </div>
        <ul>
          <li v-for="(stations, province) in groupedStations" :key="province" @click="selectProvince(province)">
            {{ province }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 二级菜单：选择站点（模态框样式） -->
    <div v-if="isStationSelectorVisible" class="station-selector-overlay">
      <div class="station-selector">
        <div class="station-header">
          <span>选择站点 - {{ selectedProvince }}</span>
          <button @click="closeStationSelector">关闭</button>
        </div>
        <ul>
          <li v-for="station in groupedStations[selectedProvince]" :key="station['区站号']" @click="selectStation(station)">
            {{ station['站名'] }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 图表展示区域 -->
    <div v-if="isChartsVisible">
      <div ref="temperatureChart" :style="{ width: '100%', height: '400px', marginBottom: '20px' }"></div>
      <div ref="pressureChart" :style="{ width: '100%', height: '400px', marginBottom: '20px' }"></div>
      <div ref="humidityChart" :style="{ width: '100%', height: '400px' }"></div>
    </div>

    <!-- 地图展示区域 -->
    <div v-show="isMapVisible" ref="mapChart" :style="{ width: '100%', height: '600px' }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts/extension/bmap/bmap';
import axios from 'axios';
import stationData from '@/data/stationData.json'; // 引入站点数据

export default {
  name: 'WeatherChart',
  data() {
    return {
      stationNameInput: '',
      isLocationSelectorVisible: false,
      isStationSelectorVisible: false,
      isChartsVisible: true, // 控制图表显示与否
      isMapVisible: false, // 控制地图显示与否
      currentStationId: null, // 当前查询的站点ID
      groupedStations: {},
      selectedProvince: null,
      map: null, // 百度地图实例
      points: [] // 存储站点坐标的点
    };
  },
  mounted() {
    // 在挂载组件时将站点按省份分组
    this.groupedStations = this.groupStationsByProvince();
  },
  methods: {
    groupStationsByProvince() {
      const grouped = {};
      stationData.forEach((station) => {
        const province = station['省份'];
        if (!grouped[province]) {
          grouped[province] = [];
        }
        grouped[province].push(station);
      });
      return grouped;
    },
    toggleLocationSelector() {
      this.isLocationSelectorVisible = !this.isLocationSelectorVisible;
      this.selectedProvince = null; // 重置选中的省份
    },
    selectProvince(province) {
      this.selectedProvince = province;
      this.isStationSelectorVisible = true; // 显示二级菜单
    },
    closeStationSelector() {
      this.isStationSelectorVisible = false;
    },
    selectStation(station) {
      this.stationNameInput = station['站名'];
      this.isStationSelectorVisible = false;
      this.isLocationSelectorVisible = false;
      this.fetchWeatherDataById(station['区站号']);
    },
    toggleChartsVisibility() {
      this.isChartsVisible = !this.isChartsVisible;

      // 当图表可见时，重新调用 API 查询当前站点数据并绘制图表
      if (this.isChartsVisible && this.currentStationId) {
        this.fetchWeatherDataById(this.currentStationId);
      }
    },
    toggleMapVisibility() {
      this.isMapVisible = !this.isMapVisible;

      // 确保地图实例只初始化一次
      if (this.isMapVisible) {
        this.$nextTick(() => {
          this.initBaiduMap(); // 确保在地图 DOM 渲染后再初始化地图
        });
      }
    },
    fetchWeatherDataByName() {
      const station = stationData.find((item) => item['站名'] === this.stationNameInput);
      if (station) {
        this.fetchWeatherDataById(station['区站号']);
      } else {
        console.error('未找到相关站名');
      }
    },
    fetchWeatherDataById(stationID) {
      this.currentStationId = stationID; // 存储当前站点ID
      const requestUrl = `http://localhost:8080/api/weather/${stationID}`;
      axios
          .get(requestUrl)
          .then((response) => {
            if (response && response.data && response.data.code === 0) {
              this.renderCharts(response.data.data, stationID);
            } else {
              console.error('未接收到有效的气象数据');
            }
          })
          .catch((error) => {
            console.error('无法获取气象数据:', error);
          });
    },
    renderCharts(weatherData, stationID) {
      // 确保获取到的数据不为空并且包含有效数据
      if (!weatherData || !Array.isArray(weatherData) || weatherData.length === 0) {
        console.error('没有有效的气象数据');
        return;
      }

      // 准备要展示的数据
      const timeLabels = weatherData.map((data) => `${data.Year}-${data.Mon}-${data.Day} ${data.Hour}:00`);
      const temperatureData = weatherData.map((data) => parseFloat(data.TEM));
      const pressureData = weatherData.map((data) => parseFloat(data.PRS));
      const humidityData = weatherData.map((data) => parseInt(data.RHU));

      const station = stationData.find((item) => item['区站号'] === stationID);
      const stationName = station ? station['站名'] : '未知站点';

      echarts.use(['bmap', 'scatter']);

      // 初始化温度图表
      this.initTemperatureChart(timeLabels, temperatureData, stationName);

      // 初始化气压图表
      this.initPressureChart(timeLabels, pressureData, stationName);

      // 初始化湿度图表
      this.initHumidityChart(timeLabels, humidityData, stationName);
    },
    initTemperatureChart(timeLabels, temperatureData, stationName) {
      const myChart = echarts.init(this.$refs.temperatureChart);
      const option = {
        title: {
          text: `${stationName}气象数据 - 温度变化`,
          subtext: '数据来源：中国气象局',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} °C',
        },
        xAxis: {
          type: 'category',
          data: timeLabels,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
        },
        series: [
          {
            name: '温度 (°C)',
            type: 'line',
            data: temperatureData,
            itemStyle: {
              color: '#FF7F50',
            },
          },
        ],
      };
      myChart.setOption(option);
    },
    initPressureChart(timeLabels, pressureData, stationName) {
      const myChart = echarts.init(this.$refs.pressureChart);
      const option = {
        title: {
          text: `${stationName}气象数据 - 气压变化`,
          subtext: '数据来源：中国气象局',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} 百帕',
        },
        xAxis: {
          type: 'category',
          data: timeLabels,
          axisLabel: { rotate: 45 },
        },
        yAxis: { type: 'value', name: '气压 (百帕)' },
        series: [
          {
            name: '气压 (百帕)',
            type: 'line',
            data: pressureData,
            itemStyle: { color: '#6495ED' },
          },
        ],
      };
      myChart.setOption(option);
    },
    initHumidityChart(timeLabels, humidityData, stationName) {
      const myChart = echarts.init(this.$refs.humidityChart);
      const option = {
        title: {
          text: `${stationName}气象数据 - 相对湿度变化`,
          subtext: '数据来源：中国气象局',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} %',
        },
        xAxis: {
          type: 'category',
          data: timeLabels,
          axisLabel: { rotate: 45 },
        },
        yAxis: { type: 'value', name: '相对湿度 (%)' },
        series: [
          {
            name: '相对湿度 (%)',
            type: 'bar',
            data: humidityData,
            itemStyle: { color: '#87CEFA' },
          },
        ],
      };
      myChart.setOption(option);
    },
    initBaiduMap() {
      if (!this.map) {
        this.map = new BMapGL.Map(this.$refs.mapChart); // 初始化地图实例
        const point = new BMapGL.Point(104.114129, 37.550339); // 设置地图中心点
        this.map.centerAndZoom(point, 5); // 设置地图级别
        this.map.enableScrollWheelZoom(true); // 启用鼠标滚轮缩放
        this.loadStationPoints(); // 加载站点坐标
      }
    },
    loadStationPoints() {
      stationData.forEach((station) => {
        const point = new BMapGL.Point(station['经度'], station['纬度']);
        const marker = new BMapGL.Marker(point); // 创建标记
        this.map.addOverlay(marker); // 将标记添加到地图
        this.points.push(point);
      });
    }
  }
};
</script>
<style scoped>
.location-selector-overlay,
.station-selector-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.location-selector,
.station-selector {
  background: white;
  padding: 20px;
  width: 300px;
  max-height: 400px;
  overflow-y: auto;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.location-header,
.station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.location-header button,
.station-header button {
  border: none;
  background: none;
  cursor: pointer;
}
</style>
